package com.mt.roll.core.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * 压缩文件的工具类(zip压缩)
 * </p>
 *
 * @author Mr.ZhangShi
 * @date 2019/3/14
 * @since 1.0
 */
public class ZipUtils {

    private ZipUtils() {
    }

    public static void doCompress(String srcFile, String zipFile) throws IOException {
        doCompress(new File(srcFile), new File(zipFile));
    }

    /**
     * 文件压缩
     *
     * @param srcFile 目录或者单个文件
     * @param zipFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException {
        doCompress(new File(filelName), out);
    }

    /**
     * 支持单个文件自定义文件名压缩(
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     * @param out
     * @throws IOException
     */
    public static void doCompress(String filePath, String fileName, ZipOutputStream out) throws IOException {
        ZipUtils.doZip(new File(filePath), fileName, out, "");
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException {
        doCompress(file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if (inFile.isDirectory()) {
            File[] files = inFile.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    ZipUtils.doCompress(file, out, name);
                }
            }
        } else {
            ZipUtils.doZip(inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        doZip(inFile, "", out, dir);
    }

    public static void doZip(File inFile, String fileName, ZipOutputStream out, String dir) throws IOException {
        String entryName;
        if (StringUtils.isEmpty(fileName)) {
            fileName = inFile.getName();
        }
        if (StringUtils.isNotEmpty(dir)) {
            entryName = dir + "/" + fileName;
        } else {
            entryName = fileName;
        }
        ZipEntry entry = new ZipEntry(entryName);
        out.putNextEntry(entry);

        int len = 0;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(inFile);
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }

    public static void zipFile(HttpServletResponse response, List<Map<String, String>> list) throws Exception {
        ZipOutputStream out = null;
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(("医诺云检" + DateUtil.getCurrentDateTimeNow() + ".zip").getBytes("GBK"), "ISO8859_1"));
        //设置压缩流：直接写入response，实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipos.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法
        } catch (Exception e) {
            e.printStackTrace();
        }
        DataOutputStream os = null;
        //循环将文件写入压缩流
        for (Map map : list) {
            String filePath = map.get("fileUrl").toString();
            String fileName = map.get("fileName").toString();
            File file = new File(filePath);//要下载文件的路径
            try {
                //添加ZipEntry，并ZipEntry中写入文件流
                //这里，加上i是防止要下载的文件有重名的导致下载失败
                zipos.putNextEntry(new ZipEntry(fileName));
                os = new DataOutputStream(zipos);
                InputStream is = new FileInputStream(file);
                byte[] b = new byte[100];
                int length = 0;
                while ((length = is.read(b)) != -1) {
                    os.write(b, 0, length);
                }
                is.close();
                zipos.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        os.flush();
        os.close();
        zipos.close();
    }
}
